package www.study.com;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//四数之和 https://leetcode.cn/problems/4sum/
public class code17 {
    public static void main(String[] args) {

    }

    class Solution {
        public List<List<Integer>> fourSum(int[] nums, int target) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            if(nums.length < 4) return res;
            Arrays.sort(nums);
            for(int i = 0 ; i <= nums.length - 4 ; i++){
                if(i > 0 && nums[i - 1] == nums[i]) continue;
                //如果后四个数字小于target，说明这个i过小，i右移
                if((long)nums[i] + nums[nums.length - 1] + nums[nums.length - 2] + nums[nums.length - 3] < (long)target) continue;
                //如果前四个数字大于target，说明之后所有组合都会大于target，直接返回即可
                if((long)nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > (long)target) break;
                for(int j = i + 1 ; j <= nums.length - 3 ; j++){
                    if(j > i + 1 && nums[j] == nums[j - 1]) continue;
                    int lef = j + 1;
                    int rig = nums.length - 1;
                    while(lef < rig){
                        //while(nums[lef] == nums[rig] && lef < rig) lef++;
                        if((long)nums[i] + nums[j] + nums[lef] + nums[rig] == (long)target){
                            res.add(new ArrayList(Arrays.asList(nums[i], nums[j], nums[lef], nums[rig])));
                            //注意下面两个while不能放在3位置，因为while的意思是当凑出结果后去重
                            while(lef < rig && nums[lef] == nums[lef + 1]) lef++;
                            while(lef < rig && nums[rig] == nums[rig - 1]) rig--;
                            //continue;
                        }
                        //3
                        if((long)nums[i] + nums[j] + nums[lef] + nums[rig] > (long)target) rig--;
                        else lef++;
                    }
                }
            }
            return res;
        }
    }
}
